package com.dwxt.cdms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dwxt.cdms.base.Page;
import com.dwxt.cdms.dao.YouthHopeMapper;
import com.dwxt.cdms.entity.EquipmentCustom;
import com.dwxt.cdms.entity.YouthHope;
import com.dwxt.cdms.entity.vo.YouthHopeVO;
import com.dwxt.cdms.entity.witheart.*;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.util.JsonUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.zip.GZIPOutputStream;

@Service
public class YouthHopeService {


    @Autowired
    private YouthHopeMapper youthHopeMapper;

    @Autowired
    private EquipmentCustomService equipmentCustomService;

    @Autowired
    private StationService stationService;

    @Value("${witheart.token}")
    private String witheartToken;

    @Value("${witheart.deptid}")
    private String deptid;

    private final static Logger logger = LoggerFactory.getLogger(YouthHopeService.class);

    public BaseResult receiveData(YouthHope youthHopeParam) throws IOException {
        logger.error("接收到心晓数据:" + youthHopeParam.getReportid() + "::" + youthHopeParam);
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("reportid", youthHopeParam.getReportid());
        paramMap.put("page", "1");
        paramMap.put("size", "1");
        paramMap.put("deptid",deptid);
        String uri = "/lite/Admin/ReportDetailList";
        JSONObject jsonObject = getWitheartData(paramMap, uri);
        JSONObject data = (JSONObject) jsonObject.get("data");
        Object data1 = data.get("data");
        List<YouthHope> list = JSON.parseArray(JSON.toJSONString(data1), YouthHope.class);
        if (list.size() == 0 || list == null) {
            return BaseResult.ok();
        }
        YouthHope youthHope = list.get(0);
        EquipmentCustom equipmentCustom = equipmentCustomService.selectEquipmentCustomByDeviceIdentity(youthHope.getSn());
        if (equipmentCustom == null) {
            return BaseResult.ok();
        }
        youthHope.setCustomerId(equipmentCustom.getCustomerId());
        youthHope.setReporturl(youthHopeParam.getReporturl());
        youthHope.setGenre(youthHopeParam.getGenre());
        youthHopeMapper.insert(youthHope);
        return BaseResult.ok();
    }

    public JSONObject getWitheartData(Map paramMap, String uri) throws IOException {
        String url = "http://api.ryouhu.senviv.com"+uri;
        String paramMapStr = JsonUtils.objectToJson(paramMap);
        //压缩
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(paramMapStr.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //加密
        String encode = new BASE64Encoder().encode(out.toByteArray()).replaceAll("\r|\n", "");
        Map<String, String> map = new HashMap<>();
        map.put("token", witheartToken);
        map.put("data", encode);
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(map));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Cache-Control", "no-cache")
                .build();

        Response response = client.newCall(request).execute();
        String res = response.body().string();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = JSONObject.parseObject(res);
        } catch (Exception e) {
            jsonObject.put("data", res);
            jsonObject.put("code", 0);
            return jsonObject;
        }
        return jsonObject;
    }

    public BaseResult selectYoutHopePageGroup(Page page, String name) {
        Integer stationId = stationService.getLoginUserStation();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<YouthHope> youthHopes = youthHopeMapper.selectYoutHopePageGroup(name, stationId);
        List<YouthHopeVO> voList = youthHopes.stream().map(youthHope -> {
            YouthHopeVO vo = new YouthHopeVO();
            BeanUtils.copyProperties(youthHope, vo);
            vo.setReport(JSON.parseObject(youthHope.getReport(), Report.class));
            return vo;
        }).collect(Collectors.toList());
        PageInfo<YouthHopeVO> youthHopePageInfo = new PageInfo<>(voList);
        return BaseResult.ok(youthHopePageInfo);
    }


    public BaseResult selectYoutHopePage(Page page, Integer customerId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<YouthHope> youthHopes = youthHopeMapper.selectPageByCustomerId(customerId);
        List<YouthHopeVO> voList = youthHopes.stream().map(youthHope -> {
            YouthHopeVO vo = new YouthHopeVO();
            BeanUtils.copyProperties(youthHope, vo);
            vo.setReport(JSON.parseObject(youthHope.getReport(), Report.class));
            return vo;
        }).collect(Collectors.toList());
        PageInfo<YouthHopeVO> youthHopePageInfo = new PageInfo<>(voList);
        return BaseResult.ok(youthHopePageInfo);
    }


    public YouthHopeVO entity2VO(YouthHope youthHope) {
        if (youthHope != null) {
            YouthHopeVO youthHopeVO = new YouthHopeVO();
            BeanUtils.copyProperties(youthHope, youthHopeVO);
            youthHopeVO.setReport(JSON.parseObject(youthHope.getReport(), Report.class));
            youthHopeVO.setReportcharts(JSON.parseObject(youthHope.getReportcharts(), ReportCharts.class));
            youthHopeVO.setReportofbreath(JSON.parseObject(youthHope.getReportofbreath(), ReportOfBreath.class));
            youthHopeVO.setReportofheartbeat(JSON.parseObject(youthHope.getReportofheartbeat(), ReportOfHeartBeat.class));
            youthHopeVO.setReportofhrv(JSON.parseObject(youthHope.getReportofhrv(), ReportOfHRV.class));
            youthHopeVO.setReportofoffbed(JSON.parseObject(youthHope.getReportofoffbed(), ReportOfOffbed.class));
            youthHopeVO.setReportofsleep(JSON.parseObject(youthHope.getReportofsleep(), ReportOfSleep.class));
            youthHopeVO.setUserbaseinfo(JSON.parseObject(youthHope.getUserbaseinfo(), UserBaseInfo.class));
            return youthHopeVO;
        }
        return null;
    }

    public BaseResult selectYoutHopeById(Integer id) {
        YouthHope youthHope = youthHopeMapper.selectYoutHopeById(id);
        return BaseResult.ok(youthHope);
    }

    /**
     * 根据日期和用户id查询当天最新数据
     *
     * @param customerId
     * @param dayTime
     * @return
     */
    public BaseResult selectYoutHopeByCustomerIdAndTime(Integer customerId, String dayTime) {
        YouthHope youthHope = youthHopeMapper.selectYoutHopeByCustomerIdAndTime(customerId, dayTime);
        if (youthHope != null) {
            return BaseResult.ok(youthHope);
        } else {
            return BaseResult.build(StatusCode.SELECT_INFO_ISNOT_EXIST);
        }
    }

    public YouthHopeVO selectNewDataByCustomerId(Integer customerId) {
        return entity2VO(youthHopeMapper.selectNewDataByCustomerId(customerId));
    }
}
